package main

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
	"net"
	"os"
	"os/signal"
	"syscall"

	"user_srv/global"
	_ "user_srv/initialize"
	"user_srv/logic"
	"user_srv/user_proto"
)

func main() {
	zap.S().Info(global.ServerConfig)
	g := grpc.NewServer()
	user_proto.RegisterUserServer(g, &logic.Server{})
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", global.ServerConfig.IP, global.ServerConfig.Port))
	if err != nil {
		zap.S().Error(err)
	}
	//注册服务健康检查
	grpc_health_v1.RegisterHealthServer(g, health.NewServer())
	go func() {
		err := g.Serve(listen)
		if err != nil {
			zap.S().Panic(err)
		}
	}()
	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	config := api.DefaultConfig()
	config.Address = fmt.Sprintf("%s:%d", global.ServerConfig.ConsulConfig.ConsulHost, global.ServerConfig.ConsulConfig.ConsulPort)
	client, err := api.NewClient(config)
	if err != nil {
		return
	}
	err = client.Agent().ServiceDeregister(global.ServerID)
	if err != nil {
		fmt.Println("服务注销失败")
	}
	fmt.Println("服务注销成功")
}
